package com.example.cardgame

import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.cardgame.GameFrame.Companion
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream


class GameActivity : Fragment(){
//    val cardButtons= mutableListOf<Button>()
    lateinit var adapter:CardAdapter
    private var callback: DataCallback2? = null
    override fun onCreateView(
        inflater: LayoutInflater,container:ViewGroup?,savedInstanceState: Bundle?
    ):View?{
        return inflater.inflate(R.layout.activity_game,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val rgame:CardMatchingGame?=loadData()
        if(rgame!=null){
            game=rgame
        }else{
            game=CardMatchingGame(24)
        }
        adapter=CardAdapter(game)
        var recyclerView=view.findViewById<RecyclerView>(R.id.recycleView)
        recyclerView.adapter=adapter
        val configure=resources.configuration
        if(configure.orientation==Configuration.ORIENTATION_PORTRAIT){
            recyclerView.layoutManager=GridLayoutManager(activity,4)
        }else{
            recyclerView.layoutManager=GridLayoutManager(activity,6)
        }
        updateUI()
        adapter.setOnClickListener {
            game.chooseCardAtIndex(it)
            updateUI()

        }
        ViewCompat.setOnApplyWindowInsetsListener(view.findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val recycle_button=view.findViewById<Button>(R.id.recycle_button)
        recycle_button.setOnClickListener{
            val myDataObject = MyData(game.score)
            callback?.onDataReceived2(myDataObject)
            game.reset()
            updateUI()
        }
        val scoreText=view.findViewById<TextView>(R.id.score_text)

    }
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 确保宿主Activity实现了DataCallback接口
        if (context is DataCallback) {
            callback = context as DataCallback2
        } else {
            throw RuntimeException("$context must implement DataCallback")
        }
    }
    override fun onDetach() {
        super.onDetach()
        callback = null // 清理引用，避免内存泄漏
    }
    fun updateUI(){
        adapter.notifyDataSetChanged()
        val score_text=view?.findViewById<TextView>(R.id.score_text)
        score_text?.text=String.format("%d",game.score)
    }
    override fun onStop(){
        super.onStop()
        saveData()
    }
    fun saveData(){
        try {
            val output:FileOutputStream?=activity?.openFileOutput("data",AppCompatActivity.MODE_PRIVATE)
            val objectOutputStream=ObjectOutputStream(output)
            objectOutputStream.writeObject(game)
            objectOutputStream.close()
            output?.close()
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
    fun loadData():CardMatchingGame?{
        try {
            val input:FileInputStream?=activity?.openFileInput("data")
            val objectInputStream= ObjectInputStream(input)
            val game:CardMatchingGame=objectInputStream.readObject() as CardMatchingGame
            objectInputStream.close()
            input?.close()
            return game
        }catch (e:Exception){
            e.printStackTrace()
            return null
        }
    }
    companion object{
        lateinit var game: CardMatchingGame
        @JvmStatic
        fun newInstance():GameActivity=GameActivity()
    }
}